package com.baijiayun.liveuibase.widgets.courseware;

import android.annotation.SuppressLint;

import com.baijiayun.livecore.alilog.AliYunLogHelper;
import com.baijiayun.livecore.models.file.homework.LPHomeworkModel;
import com.baijiayun.livecore.utils.LPJsonUtils;
import com.baijiayun.liveuibase.utils.BaseUIUtils;
import com.tencent.mmkv.MMKV;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

import static com.baijiayun.liveuibase.base.BaseUIConstant.homeworkDirPath;


public class HomeworkSaveUtil {
    private static final String TAG = HomeworkSaveUtil.class.getSimpleName();
    private final MMKV mmkv = MMKV.mmkvWithID("BJY_HOMEWORK");

    @SuppressLint("CheckResult")
    public HomeworkSaveUtil() {
        Observable.empty().subscribeOn(Schedulers.io()).subscribe(o -> initMessageFile());
    }

    /**
     * 保存作业相关信息
     */
    public void saveHomework(SaveMessageModel saveMessageModel) {
        String homeworkName = BaseUIUtils.getHomeworkFileName(saveMessageModel.homeworkModel) + saveMessageModel.homeworkModel.getFext();
        String data = LPJsonUtils.toJsonObject(saveMessageModel).toString();
        mmkv.encode(homeworkName, data);
    }

    /**
     * 初始化额外信息保存目录
     */
    private void initMessageFile() {
        File dir = new File(homeworkDirPath);
        if (!checkDir(dir)) {
            // 如果不存在该目录，且目录创建失败，结束
            return;
        }
        try {
            for (String allKey : mmkv.allKeys()) {
                File file = new File(homeworkDirPath + allKey);
                if (!file.exists()) {
                    // 如果文件已不存在，移除这个key
                    mmkv.remove(allKey);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查文件目录是否存在， 不存在则创建
     * @return 返回最终是否存在结果
     */
    private boolean checkDir(File dir) {
        boolean exist = dir.isDirectory();
        if (!exist) {
            try {
                exist = dir.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exist;
    }

    public static class SaveMessageModel {
        String className;
        long roomId;
        LPHomeworkModel homeworkModel;

        public SaveMessageModel(String className, long roomId, LPHomeworkModel homeworkModel) {
            this.className = className;
            this.roomId = roomId;
            this.homeworkModel = homeworkModel;
        }
    }
}
